package com.qf.cx.simplenms.core.spi.impl;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.function.Consumer;

import org.springframework.beans.factory.annotation.Autowired;

import com.qf.cx.simplenms.core.spi.Updater;
import com.qf.cx.simplenms.core.util.ModelUtils;
import com.qf.cx.simplenms.persist.entity.AntennaEntity;
import com.qf.cx.simplenms.persist.entity.ReaderGroupEntity;
import com.qf.cx.simplenms.persist.service.api.ReaderGroupService;
import com.qf.cx.simplenms.reader.model.AntennaModel;
import com.qf.cx.simplenms.reader.model.ReaderModel;
import com.qf.cx.simplenms.readergroup.api.ReaderGroupManager;
import com.qf.cx.simplenms.readergroup.model.ReaderGroupModel;

public class ReaderGroupUpdater implements Updater {
	@Autowired
	private ReaderGroupService readerGroupService;

	@Autowired
	private ReaderGroupManager readerGroupManager;

	@Override
	public void update() {
		List<ReaderGroupEntity> readerGroups = readerGroupService.getReaderGroups();
		List<ReaderGroupModel> list = new ArrayList<>();
		readerGroups.forEach(new Consumer<ReaderGroupEntity>() {
			@Override
			public void accept(final ReaderGroupEntity t) {
				ReaderGroupModel readerGroup = new ReaderGroupModel();
				readerGroup.setName(t.getName());
				List<AntennaEntity> antennaEntities = t.getAntennaEntities();
				Set<AntennaModel> antennas = new HashSet<>(antennaEntities.size());
				antennaEntities.forEach(t2 -> {
					ReaderModel readerModel = ModelUtils.createReaderModel(t2.getReaderEntity());
					AntennaModel ant = ModelUtils.createAntennaModel(readerModel, t2);
					antennas.add(ant);
				});
				readerGroup.setAntennas(antennas);
				list.add(readerGroup);
			}
		});
		readerGroupManager.updateCache(list);
	}

}
